package cn.com.fone.modules.api.app.controller;


import cn.com.fone.modules.api.app.entity.UserEntity;
import cn.com.fone.modules.api.app.form.LoginForm;
import cn.com.fone.modules.api.app.service.UserService;
import cn.com.fone.modules.api.app.utils.JwtUtils;
import cn.com.fone.modules.api.common.validator.ValidatorUtils;
import cn.com.fone.util.R;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-23 15:31
 */
@RestController
@RequestMapping("/app")
@Api("APP-用户管理")
public class AppUserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 用户-登录
     */
    @PostMapping("login")
    @ApiOperation("用户-登录")
    public R login(@RequestBody LoginForm form) {
        // 表单校验
        ValidatorUtils.validateEntity(form);

        // 用户登录
        long userId = userService.login(form);

        // 生成token
        String token = jwtUtils.generateToken(userId);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());

        return R.ok(map);
    }

    /**
     * 用户-根据手机号获取用户信息
     */
    @PostMapping("getUserByMobile")
    @ApiOperation("用户-根据手机号获取用户信息")
    public R getUserByMobile(@RequestBody String mobile) {
        return R.ok(JSONObject.toJSONString(userService.queryByMobile(mobile)));
    }


    /**
     * 用户-根据ID更新用户信息
     */
    @PostMapping("updateUserById")
    @ApiOperation("用户-根据用户ID更新用户信息")
    public R updateUserById(@RequestBody UserEntity userEntity) {
        return R.ok(JSONObject.toJSONString(userService.updateUserById(userEntity)));
    }
}
